//
// Created by lanlu on 2025/8/7.
//

#include <vector>
#include <stack>
#include <iostream>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr)
    {
    }

    TreeNode(int x) : val(x), left(nullptr), right(nullptr)
    {
    }

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right)
    {
    }
};

class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root)
    {
        vector<int> result;
        if (root == nullptr) return result;
        // 可以在栈中节点上 保存一个标记 bool true表示已经处理完左右子树 false表示未处理
        stack<pair<TreeNode *, bool> > s;
        s.push(make_pair(root, false));

        while (!s.empty())
        {
            // 取出栈顶元素
            auto [node, flag] = s.top();
            s.pop();
            if (!flag)
            {
                // 节点标记为已处理
                s.push(make_pair(node, true));
                if (node->right)
                {
                    s.push(make_pair(node->right, false));
                }
                if (node->left)
                {
                    s.push(make_pair(node->left, false));
                }
            }
            else
            {
                result.push_back(node->val);
            }
        }

        return result;
    }
};


int main()
{
    TreeNode *root = new TreeNode(1);
    root->right = new TreeNode(2);
    root->right->left = new TreeNode(3);

    vector<int> v = Solution().postorderTraversal(root);
    for (int i: v)
    {
        cout << i << " ";
    }
    cout << endl;
}
